package com.fit.pages.client;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.client.ClientDAO;
import com.fit.entities.Client;

@UserAccess
@AdminAccess
public class InsertClient {

	@Property
	@SessionState(create = false)
	private Client client;

	@Inject
	private ClientDAO clientDAO;

	@Component
	private Form createForm;

	@Persist
	@Property
	private String error;

	@Persist
	@Property
	private String confirmation;
	

	void onPrepare() {
		client = new Client();
	}

	Object onSubmitFromCreateForm() {
		error="";
		confirmation="";
		Client temp = clientDAO.findByPersonalId(client.getPersonalId());
		
		if (temp == null) {
			if (clientDAO.save(client)) {
				confirmation = "Client successfully inserted!";
				return null;
			}
			confirmation = "Client is null!";
			return null;
		}

		error = "Client with " + client.getId()
				+ " ID already exists!";

		return null;
	}

	@OnEvent(component = "ResetConfLink")
	Object onResetConfLink() {
		confirmation = "";
		return null;
	}

	@OnEvent(component = "ResetErrorLink")
	Object onResetErrorLink() {
		error = "";
		return null;
	}

	public boolean isErrorNotNull() {
		if (error == null || error == "") {
			return false;
		}
		return true;
	}

	public boolean isConfirmationNotNull() {
		if (confirmation == null || confirmation == "") {
			return false;
		}
		return true;
	}

}
